﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Util;
using ZLCMS.Data.Model;
using NHibernate.Criterion;
using ZLCMS.Business.TranferParam;
using ZLCMS.Web.SystemManage.Control;
using System.Collections.Generic;
using Newtonsoft.Json;
using NHibernate;
using DotNet.Common.TransferParam;
using DotNet.Common.NHibernateUtil;
using DotNet.Common.Command;
using ZLCMS.Commands.User.Commands.ProductSku;
using ZLCMS.Commands.Data;
using ZLCMS.Commands.User.Util;

namespace ZLCMS.Web.SystemManage.Basics.ProductSKU
{
    public partial class ProductEdit : System.Web.UI.Page
    {
        protected FrameHelper _framePage;
        public string _userAccount;
        protected ShopProductInfo _productDB;
        protected ShopCategory _categoryDB;
        protected List<ShopSkuGroup> groups;
        private List<ShopCategory> _list;
        public string _deptCode;
        protected void Page_Load(object sender, EventArgs e)
        {
            //初始化DWZ控件
            _framePage = new FrameHelper(this);
            _userAccount = UserKit.GetUserAccountFailLogin();

            if (!AuthUtil.CheckAuthorization("PRODUCT_MAN", "EDIT", _userAccount) )
            {
                _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作失败-权限不足!" });
                return;
            }

            //初始化全局变量值
            InitializeGlobalValue();

            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                SaveProduct();
            }
        }

        #region 初始化全局变量 + protected void InitializeGlobalValue()
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        protected void InitializeGlobalValue()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                try
                {
                    if (!IsPostBack)
                    {
                        _id.Text = Request["pid"];

                        IList<SysDepartmentInfo> deptList = session.CreateQuery("from SysDepartmentInfo").List<SysDepartmentInfo>();

                        if (AuthUtil.CheckAuthorization("DEPT_MAN", "ALL", _userAccount))
                        {
                            _deptCode = "";
                        }
                        else if (AuthUtil.CheckAuthorization("DEPT_MAN", "VIEW_OWNER", _userAccount))
                        {
                            _deptCode = session.CreateSQLQuery("select dept_code from sys_user_info where user_account=:acc")
                            .SetParameter("acc", _userAccount).UniqueResult<string>();
                            deptList = session.CreateQuery("from SysDepartmentInfo where DeptCode=:code ").SetParameter("code", _deptCode).List<SysDepartmentInfo>();
                        }
                        else
                        {
                            //没有权限访问
                            _deptCode = "-1";
                        }

                        ddl_dept.DataSource = deptList;
                        ddl_dept.DataValueField = "DeptCode";
                        ddl_dept.DataTextField = "DeptName";
                        ddl_dept.DataBind();
                    }


                    _productDB = session.Get<ShopProductInfo>(int.Parse(_id.Text));
                    if (_productDB == null)
                    {
                        throw new Exception("找不到对应信息.");
                    }
                    _categoryDB = session.Get<ShopCategory>(_productDB.TypeId);

                    if (!IsPostBack && _categoryDB != null)
                    {
                        ddl_producttype.SelectedNodeId = _categoryDB.Id;
                        ddl_producttype.SelectedNodeText = _categoryDB.CategoryName;
                    }
                    if (!string.IsNullOrEmpty(_productDB.CustomField) && _productDB.CustomField != "[]")
                        groups = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CustomData>>(_productDB.CustomField).Select(gl => gl.Group).ToList();
                    else
                        groups = new List<ShopSkuGroup>();

                }
                catch (System.Exception ex)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }
        }
        #endregion

        #region 初始化产品信息 + 初始化产品信息
        /// <summary>
        /// 初始化产品信息
        /// </summary>
        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                tb_name.Text = _productDB.ProductName;
                tb_productno.Text = _productDB.ProductNo;
                if (string.IsNullOrEmpty(_productDB.TagIds))
                {
                    cbk_user_tag.Checked = false;
                }
                else
                {
                    cbk_user_tag.Checked = true;
                }
                tb_shortdesc.Text = _productDB.ShortDesc;
                tb_mprice.Text = _productDB.MarketPrice.ToString();
                tb_sprice.Text = _productDB.SalePrice.ToString();
                tb_score.Text = _productDB.Score.ToString();
                tb_storage.Text = _productDB.Storage.ToString();
                txtParamContent.Value = _productDB.ParamContent;
                tb_interior_code.Text = _productDB.InteriorCode;
                ParamKit.Bind("ProductKind", e_ddl_product_kind, null, null, null, _productDB.Kind, _productDB.Kind);
                e_cbx_is_limit.Checked = _productDB.IsLimitTime == "1";
                e_tb_end_time.Text = string.Format("{0:yyyy-MM-dd}", _productDB.EndTime);
                e_tb_rule_id.Text = _productDB.KindRuleId.ToString();

                fc_open.Value = _productDB.ThumbnailImg;

                fc_open.Config = new Business.UploadFileInfo.UploadConfig()
                {
                    Thumbnail = new ThumbnailConfig()
                    {
                        Mode = "HW",
                        Auto = true,
                        Name = "thumb",
                        Height = 300,
                        Width = 300
                    },
                    UploadDir = _userAccount + "/product/"
                };
                fc_relatedimgs.Value = _productDB.ProductImg;

                txt_description.Value = _productDB.Description;
                hid_tids.Value = _productDB.TagIds;
                ckb_available_coupon.Checked = (_productDB.AvailableCoupon == 1);
                ddl_dept.SelectedValue = _productDB.DeptCode;
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    if (_categoryDB != null)
                    {
                        //获取标签
                        rpt_tag.DataSource = session.CreateQuery("from ShopTagInfo where Status!='9' ").List<ShopTagInfo>();
                        rpt_tag.DataBind();

                        rp_skugroup.DataSource = GetSkuGroups(session, _categoryDB);
                        rp_skugroup.DataBind();


                        //分类搜索属性
                        IList<ShopSearchPropertyGroup> list = new List<ShopSearchPropertyGroup>();

                        _list = new List<ShopCategory>();

                        GetParentsSearchProperty(_categoryDB.ParentId, session);

                        list = session.CreateCriteria<ShopSearchPropertyGroup>().Add(Expression.Eq("CategoryId", _categoryDB.Id)).AddOrder(NHibernate.Criterion.Order.Asc("Sort")).List<ShopSearchPropertyGroup>();

                        IList<ShopSearchPropertyGroup> currentCategorySPList = session.CreateCriteria<ShopSearchPropertyGroup>().Add(Expression.In("CategoryId", _list.Select(c => c.Id).ToList())).AddOrder(NHibernate.Criterion.Order.Asc("Sort")).List<ShopSearchPropertyGroup>();
                        foreach (ShopSearchPropertyGroup s in currentCategorySPList)
                        {
                            list.Add(s);
                        }
                        rpt_category_property.DataSource = list; 
                        rpt_category_property.DataBind();

                        IList<ShopSearchPropertyProduct> valueList = session.CreateQuery("from ShopSearchPropertyProduct where ProductNo=:pno").SetParameter("pno", _productDB.ProductNo).List<ShopSearchPropertyProduct>();
                        string valueStr = "";
                        for (int i = 0; i < valueList.Count; i++)
                        {
                            if (i == valueList.Count - 1)
                            {
                                valueStr += valueList[i].PropertyItemId;
                            }
                            else
                            {
                                valueStr += valueList[i].PropertyItemId + ",";
                            }
                        }
                        hid_property_item.Value = valueStr;
                    }
                }
            }
        }
        #endregion

        #region 保存产品 + protected void SaveProduct()
        /// <summary>
        /// 保存产品
        /// </summary>
        protected void SaveProduct()
        {
            ICommandResult<EditProductResult> res = new EditProductCommand().Execute(new EditProductParameter()
            {
                Id = _productDB.Id,
                InteriorCode = tb_interior_code.Text,
                ProductName = tb_name.Text,
                ShortDesc = tb_shortdesc.Text,
                MarketPrice = decimal.Parse(tb_mprice.Text),
                SalePrice = decimal.Parse(tb_sprice.Text),
                TagIds = cbk_user_tag.Checked ? hid_tids.Value :string.Empty ,
                Score = int.Parse(tb_score.Text),
                Storage = int.Parse(tb_storage.Text),
                ThumbnailImg = fc_open.Value,
                ProductImg = fc_relatedimgs.Value,
                Kind = e_ddl_product_kind.SelectedValue,
                IsLimitTime = e_cbx_is_limit.Checked ? "1" : "0",
                EndTime = DateTime.Parse(e_tb_end_time.Text),
                KindRuleId = int.Parse(string.IsNullOrEmpty(e_tb_rule_id.Text.Trim()) ? "0" : e_tb_rule_id.Text.Trim()),
                IsVirtual = e_ddl_product_kind.SelectedValue == "shop" ? "0" : "1",
                AddTime = DateTime.Now,
                GroundingTime = DateTime.Now,
                TypePrefix = _categoryDB.Prefix,
                Description = txt_description.Value,
                ParamContent = txtParamContent.Value,
                OwnerAccount = _userAccount,
                AvailableCoupon =ckb_available_coupon.Checked == true ? 1 : 0,
                TypeId = ddl_producttype.SelectedNodeId,
                SkuGroup = Request.Form.GetValues("sku_group"),
                PropertyItemValue = hid_property_item.Value,
                DeptCode=ddl_dept.SelectedValue
            });
            if (res.Error)
            {
                _framePage.Alert(new ReturnCode()
                {
                    statusCode = 300,
                    message = "操作失败!该内部编码已存在."
                });
            }
            else
            {
                EditProductResult resData = res.Result;
                _framePage.Alert(new ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功!",
                    callbackType = "forward",
                    forwardUrl = "/SystemManage/Basics/ProductSKU/ProductEdit.aspx?pid=" + resData.Product.Id
                });
            }
        }
        #endregion

        #region 取得该分类的所有sku组 GetParents
        /// <summary>
        /// 取得所有父节点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="session"></param>
        private List<ShopCategory> GetParents(int id, ISession session)
        {
            var list = new List<ShopCategory>();
            var parent = session.CreateCriteria<ShopCategory>().Add(Expression.Eq("Id", id)).UniqueResult<ShopCategory>();
            if (parent != null)
            {
                list.Add(parent);
                list.AddRange(GetParents(parent.ParentId, session));
            }
            return list;
        }

        /// <summary>
        /// 取得该分类的所有sku组
        /// </summary>
        /// <param name="session"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        private IList<ShopSkuGroup> GetSkuGroups(ISession session, ShopCategory category)
        {
            var list = GetParents(category.ParentId, session);
            list.Add(session.Get<ShopCategory>(_productDB.TypeId));
            var groups = session.CreateCriteria<ShopSkuGroup>().Add(Expression.In("CategoryId", list.Select(c => c.Id).ToList())).List<ShopSkuGroup>();
            return groups;
        }
        #endregion

        #region 绑定分类搜索属性列表
        /// <summary>
        /// 绑定分类搜索属性列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rpt_category_property_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //判断里层repeater处于外层repeater的哪个位置（ AlternatingItemTemplate，FooterTemplate，

            //HeaderTemplate，，ItemTemplate，SeparatorTemplate）
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rep = e.Item.FindControl("rpt_category_property_item") as Repeater;//找到里层的repeater对象
                ShopSearchPropertyGroup property = (ShopSearchPropertyGroup)e.Item.DataItem;//找到分类Repeater关联的数据项 
                using (var session = SessionFactoryHelper.CreateSession())
                {
                    rep.DataSource = session.CreateQuery("from ShopSearchPropertyItem where SearchPropertyId= :pid").SetParameter("pid", property.Id).List<ShopSearchPropertyItem>();
                    rep.DataBind();
                }
            }
        } 
        #endregion

        #region IsSelect
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string IsSelect(int id)
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                int count = Convert.ToInt32(session.CreateQuery("select count(*) from ShopSearchPropertyProduct where PropertyItemId=:id and ProductNo=:pno").SetParameter("pno", _productDB.ProductNo).SetParameter("id", id).UniqueResult());
                if (count != 0)
                {
                    return "checked=checked";
                }
                else
                {
                    return "";
                }
            }
        } 
        #endregion

        private void GetParentsSearchProperty(int id, ISession session)
        {
            var parent = session.CreateCriteria<ShopCategory>().Add(Expression.Eq("Id", id)).UniqueResult<ShopCategory>();
            if (parent != null)
            {
                _list.Add(parent);
                GetParentsSearchProperty(parent.ParentId, session);
            }
        }

        protected string IsChecked(object oid)
        {
            int id = int.Parse(oid.ToString());

            return groups.Where(g => g.Id == id).Any() ? "checked=checked" : "";
        }

    }
}
